﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Collections;
using System.Collections.Specialized;
using System.Xml;
using System.IO;
using Newtonsoft.Json.Linq;
using DCT.Huiteng.Utility.Config;

namespace DCT.Huiteng.Utility.Web
{
    public sealed class WebAPIContext
    {
        private HttpContext context;

        public WebAPIContext()
            : this(HttpContext.Current)
        {
        }

        public WebAPIContext(HttpContext context)
        {
            this.context = context;
        }

        public HttpContext Raw
        {
            get
            {
                if (this.context == null)
                {
                    throw new NullReferenceException("context为空");
                }
                return context;
            }
            set { this.context = value; } //方便单元测试的时候，可以Mock
        }

        public HttpRequest Request { get { return this.Raw.Request; } }

        public HttpResponse Response { get { return this.Raw.Response; } }

        public HttpServerUtility Server { get { return this.Raw.Server; } }

        public HttpSessionState Session { get { return this.Raw.Session; } }

        public System.Web.Caching.Cache Cache { get { return this.Raw.Cache; } }

        public IDictionary Items { get { return this.Raw.Items; } }

        public NameValueCollection GetForm()
        {
            return this.Request.Form;
        }

        public XmlDocument GetXml()
        {
            return XmlUtility.Load(this.GetRaw());
        }

        public JObject GetJson()
        {
            return JObject.Parse(this.GetRaw());
        }

        /// <summary>
        /// 根据Url创建返回格式对象，默认为Json
        /// </summary>
        /// <returns>Request.QueryString["type"]为xml为输出Xml，其余为Json</returns>
        public IConfigParser MakeResponse()
        {
            IConfigParser configParser = null;

            string responseType = this.Request.QueryString["type"];
            if (string.Compare("xml", responseType, true) == 0)
            {
                configParser = new XmlConfigParser();
            }
            else
            {
                configParser = new JsonConfigParser();
            }
            return configParser;
        }

        /// <summary>
        /// 根据配置输出内容
        /// </summary>
        /// <param name="config"></param>
        public void ResponseConfigParser(IConfigParser config)
        {
            string content = config.ParseToString();
            string contentType = "text/plain";
            if (config is XmlConfigParser) {
                ResponseXml(content);
                return;
            }
            else if (config is JsonConfigParser) {
                ResponseJson(content);
                return;
            }
            this.Response.ContentEncoding = Encoding.UTF8;            
            this.Response.ContentType = contentType;
            this.Response.Write(content);
        }

        /// <summary>
        /// 输出Xml
        /// </summary>
        /// <param name="xml"></param>
        public void ResponseXml(string xml) {
            string contentType = "text/xml;charset=utf-8";
            this.Response.ContentEncoding = Encoding.UTF8;
            this.Response.ContentType = contentType;
            this.Response.Write(xml);
        }

        /// <summary>
        /// 输出Json
        /// </summary>
        /// <param name="json"></param>
        public void ResponseJson(string json) {
            string contentType = "application/json;charset=utf-8";
            this.Response.ContentEncoding = Encoding.UTF8;
            this.Response.ContentType = contentType;
            this.Response.Write(json);
        }

        /// <summary>
        /// 获取请求的流
        /// </summary>
        /// <returns></returns>
        public String GetRaw()
        {
            string raw = "";
            using (var reader = new StreamReader(this.Request.InputStream))
            {
                raw = reader.ReadToEnd();
            }
            return raw;
        }
    }
}
